package com.tjec.project.projectWorkbench.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sun.jna.platform.win32.DdemlUtil.DdeAdapter;
import com.tjec.common.constant.AttachmentConstants;
import com.tjec.common.constant.ProjectStatus;
import com.tjec.common.enums.NumCode;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.ReflectUtils;
import com.tjec.common.utils.SecurityUtils;
import com.tjec.common.utils.ServletUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.common.utils.http.HttpUtils;
import com.tjec.framework.security.service.TokenService;
import com.tjec.framework.web.domain.AjaxResult;
import com.tjec.project.mdmSynchronous.api.HttpLocalUtils;
import com.tjec.project.mdmSynchronous.api.JSONUtils;
import com.tjec.project.mdmSynchronous.api.ThreadPost;
import com.tjec.project.mdmSynchronous.dao.ProjectDao;
import com.tjec.project.mdmSynchronous.domain.BmsProjectLeader;
import com.tjec.project.mdmSynchronous.domain.MdmUser;
import com.tjec.project.mdmSynchronous.mapper.BmsProjectLeaderMapper;
import com.tjec.project.mdmSynchronous.service.IBmsProjectLeaderService;
import com.tjec.project.mdmSynchronous.service.MdmService;
import com.tjec.project.portal.service.IBmsMsgService;
import com.tjec.project.projectLeaderWorkbeanch.domain.BmsLeaderMember;
import com.tjec.project.projectLeaderWorkbeanch.mapper.BmsLeaderMemberMapper;
import com.tjec.project.projectShowLibrary.domain.BmsProjectShowOper;
import com.tjec.project.projectShowLibrary.service.IBmsProjectShowOperService;
import com.tjec.project.projectWorkbench.domain.BmsProject;
import com.tjec.project.projectWorkbench.domain.BmsProjectContract;
import com.tjec.project.projectWorkbench.domain.BmsProjectMember;
import com.tjec.project.projectWorkbench.domain.BmsProjectSimple;
import com.tjec.project.projectWorkbench.mapper.BmsProjectMapper;
import com.tjec.project.projectWorkbench.service.IBmsProjectContractService;
import com.tjec.project.projectWorkbench.service.IBmsProjectFocusService;
import com.tjec.project.projectWorkbench.service.IBmsProjectMemberService;
import com.tjec.project.projectWorkbench.service.IBmsProjectService;
import com.tjec.project.system.domain.*;
import com.tjec.project.system.mapper.*;
import com.tjec.project.system.service.IBmsAttachmentService;
import com.tjec.project.system.service.ISysUserService;
import com.tjec.project.workflow.domain.BmsWorkflow;
import com.tjec.project.workflow.mapper.BmsWorkflowMapper;
import com.tjec.project.workflow.service.IBmsWorkflowService;

import ch.qos.logback.core.status.Status;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 项目Service业务层处理
 *
 * @author tjec
 * @date 2020-04-07
 */
@Service
public class BmsProjectServiceImpl<BmsMsgService> implements IBmsProjectService {
	private static final Logger log = LoggerFactory.getLogger(BmsProjectServiceImpl.class);

	@Autowired
	private IBmsProjectShowOperService bmsProjectShowOperService;

	@Autowired
	private BmsProjectMapper bmsProjectMapper;

	@Autowired
	private BmsAttachmentMapper bmsAttachmentMapper;

	@Autowired
	private ISysUserService iSysUserService;
	@Autowired
	private ProjectDao projectDao;
	@Autowired
	private IBmsProjectMemberService iBmsProjectMemberService;
	@Autowired
	private BmsLeaderMemberMapper bmsLeaderMemberMapper;


	@Autowired
	private IBmsProjectMemberService bmsProjectMemberService;

	@Autowired
	private MdmService mdmService;

	@Autowired
	private IBmsProjectLeaderService iBmsProjectLeaderService;

	@Autowired
	private IBmsProjectFocusService iBmsProjectFocusService;
	@Autowired
	private IBmsMsgService iBmsMsgService;

	@Autowired
	private ISysUserService sysUserService;

	@Autowired
	private TokenService tokenService;

	@Autowired
	private IBmsProjectContractService bmsProjectContractService;

	@Autowired
	private BmsWorkflowMapper bmsWorkflowMapper;

	@Autowired
	private BmsMdIndustryCategoryMapper bmsMdIndustryCategoryMapper;

	//批量插入，分页数量
	final int INSERT_BATCH_DIVISOR = 50;

	@Value("${h3bpm.systemCode}")
	private String systemCode;
	@Value("${h3bpm.secret}")
	private String secret;
	@Value("${h3bpm.baseUrl}")
	private String baseUrl;
	@Value("${h3bpm.cancelInstanceUrl}")
	private String cancelInstanceUrl;

	@Autowired
	private SysDictDataMapper sysDictDataMapper;

	@Autowired
	private BmsServiceAreaMapper bmsServiceAreaMapper;

	@Autowired
	private BmsMdBusinessCategoryMapper bmsMdBusinessCategoryMapper;

	@Autowired
	private BmsProjectLeaderMapper bmsProjectLeaderMapper;

	@Autowired
	private BmsMdAreaMapper bmsMdAreaMapper;

	@Autowired
	private IBmsAttachmentService bmsAttachmentService;

	/**
	 * 查询项目
	 *
	 * @param guid 项目ID
	 * @return 项目
	 */
	@Override
	public BmsProject selectBmsProjectByGuid(String guid) {
		BmsProject bmsProject = bmsProjectMapper.selectBmsProjectByGuid(guid);
		Set<String> serviceAreaSet = getBusinessTypeIds(guid);
		if(serviceAreaSet!=null && serviceAreaSet.size()>0) {
			List<String> res = bmsMdBusinessCategoryMapper.getBusinessTypes(serviceAreaSet);
			if(res!=null && res.size()>0) {
				String[] array2 = res.toArray(new String[res.size()]);
				bmsProject.setUseBusinessCategory(StringUtils.join(array2, "，"));
			}

		}

		return bmsProject;
	}

	public Set<String> getBusinessTypeIds(String projectId) {
		// 1、获取本项目下的服务范围
		// 2、判断有哪些大类服务范围，然后找到各小类
		// 3、根据各大类+小类从服务范围对照表里取出对应的业务类别数据
		// 4、返回业务类别信息

		Set<String> serviceAreaSet = new HashSet<String>();
		// 1、获取本项目下的服务范围
		if (projectId != null && !"".equals(projectId)) {
			BmsProject bmsProject = bmsProjectMapper.selectBmsProjectByGuid(projectId);
			/*try {
			String serviceContent = ReflectUtils
					.getValueOfGetIncludeObjectFeild(bmsProject, res.getDictValue()).toString();
			if (serviceContent != null && !"".equals(serviceContent)) {
				String[] resSec = serviceContent.split(",");
				for (String string2 : resSec) {
					// 获取服务类别对应的业务类别
					BmsServiceArea sec = bmsServiceAreaMapper.selectBmsServiceArea(res.getDictValue(),
							string2);
					if (sec != null && sec.getBusiness() != null && !"".equals(sec.getBusiness())) {
						String[] resSec2 = sec.getBusiness().split(",");
						for (String string3 : resSec2) {
							serviceAreaSet.add(string3);
						}
					}

				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}*/

			if(bmsProject != null) {
				if (bmsProject.getServiceType() != null && !"".equals(bmsProject.getServiceType())) {
					// 如果服务类别有值，再去拿出来在数据字典里判断
					String[] arr = bmsProject.getServiceType().split(",");
					for (String string : arr) {
						// 获取本服务类别的数据字典
						SysDictData res = sysDictDataMapper.getServiceDictData(string);
						// 获取服务类别对应的业务类别
						BmsServiceArea main = bmsServiceAreaMapper.selectBmsServiceArea("service_type", string);
						if (main != null && main.getBusiness() != null && !"".equals(main.getBusiness())) {
							String[] resMain = main.getBusiness().split(",");
							for (String string2 : resMain) {
								serviceAreaSet.add(string2);
							}
						}
					}
				}

				if (StringUtils.isNotBlank(bmsProject.getEngineeringConsultingService())) {
					//前期咨询服务内容
					String[] arr1 = bmsProject.getEngineeringConsultingService().split(",");
					for (String string : arr1) {
						// 获取服务类别对应的业务类别
						BmsServiceArea main = bmsServiceAreaMapper.selectBmsServiceArea("engineeringConsultingService", string);
						if (main != null && main.getBusiness() != null && !"".equals(main.getBusiness())) {
							String[] resMain = main.getBusiness().split(",");
							for (String string2 : resMain) {
								serviceAreaSet.add(string2);
							}
						}
					}
				}
				if (StringUtils.isNotBlank(bmsProject.getBiddingAgencyService())) {
					//招标代理服务内容
					String[] arr2 = bmsProject.getBiddingAgencyService().split(",");
					for (String string : arr2) {
						// 获取服务类别对应的业务类别
						BmsServiceArea main = bmsServiceAreaMapper.selectBmsServiceArea("biddingAgencyService", string);
						if (main != null && main.getBusiness() != null && !"".equals(main.getBusiness())) {
							String[] resMain = main.getBusiness().split(",");
							for (String string2 : resMain) {
								serviceAreaSet.add(string2);
							}
						}
					}
				}
				if (StringUtils.isNotBlank(bmsProject.getCostConsultingService())) {
					//造价咨询服务内容
					String[] arr3 = bmsProject.getCostConsultingService().split(",");
					for (String string : arr3) {
						// 获取服务类别对应的业务类别
						BmsServiceArea main = bmsServiceAreaMapper.selectBmsServiceArea("costConsultingService", string);
						if (main != null && main.getBusiness() != null && !"".equals(main.getBusiness())) {
							String[] resMain = main.getBusiness().split(",");
							for (String string2 : resMain) {
								serviceAreaSet.add(string2);
							}
						}
					}
				}
				if (StringUtils.isNotBlank(bmsProject.getProjectManagementService())) {
					//项目管理服务内容
					String[] arr4 = bmsProject.getProjectManagementService().split(",");
					for (String string : arr4) {
						// 获取服务类别对应的业务类别
						BmsServiceArea main = bmsServiceAreaMapper.selectBmsServiceArea("projectManagementService", string);
						if (main != null && main.getBusiness() != null && !"".equals(main.getBusiness())) {
							String[] resMain = main.getBusiness().split(",");
							for (String string2 : resMain) {
								serviceAreaSet.add(string2);
							}
						}
					}
				}
				if (StringUtils.isNotBlank(bmsProject.getProjectSupervisionService())) {
					//建设监理服务内容
					String[] arr5 = bmsProject.getProjectSupervisionService().split(",");
					for (String string : arr5) {
						// 获取服务类别对应的业务类别
						BmsServiceArea main = bmsServiceAreaMapper.selectBmsServiceArea("projectSupervisionService", string);
						if (main != null && main.getBusiness() != null && !"".equals(main.getBusiness())) {
							String[] resMain = main.getBusiness().split(",");
							for (String string2 : resMain) {
								serviceAreaSet.add(string2);
							}
						}
					}
				}
				if (StringUtils.isNotBlank(bmsProject.getEquipmentSupervisionService())) {
					//设备监理服务内容
					String[] arr6 = bmsProject.getEquipmentSupervisionService().split(",");
					for (String string : arr6) {
						// 获取服务类别对应的业务类别
						BmsServiceArea main = bmsServiceAreaMapper.selectBmsServiceArea("equipmentSupervisionService", string);
						if (main != null && main.getBusiness() != null && !"".equals(main.getBusiness())) {
							String[] resMain = main.getBusiness().split(",");
							for (String string2 : resMain) {
								serviceAreaSet.add(string2);
							}
						}
					}
				}
				if (StringUtils.isNotBlank(bmsProject.getTestingService())) {
					//检测服务服务内容
					String[] arr7 = bmsProject.getTestingService().split(",");
					for (String string : arr7) {
						// 获取服务类别对应的业务类别
						BmsServiceArea main = bmsServiceAreaMapper.selectBmsServiceArea("testingService", string);
						if (main != null && main.getBusiness() != null && !"".equals(main.getBusiness())) {
							String[] resMain = main.getBusiness().split(",");
							for (String string2 : resMain) {
								serviceAreaSet.add(string2);
							}
						}
					}
				}
				if (StringUtils.isNotBlank(bmsProject.getEiaQualificationService())) {
					//环境咨询服务内容
					String[] arr8 = bmsProject.getEiaQualificationService().split(",");
					for (String string : arr8) {
						// 获取服务类别对应的业务类别
						BmsServiceArea main = bmsServiceAreaMapper.selectBmsServiceArea("eiaQualificationService", string);
						if (main != null && main.getBusiness() != null && !"".equals(main.getBusiness())) {
							String[] resMain = main.getBusiness().split(",");
							for (String string2 : resMain) {
								serviceAreaSet.add(string2);
							}
						}
					}
				}
				if (StringUtils.isNotBlank(bmsProject.getOtherConsultingTechnicalService())) {
					//其它咨询服务内容
					String[] arr9 = bmsProject.getOtherConsultingTechnicalService().split(",");
					for (String string : arr9) {
						// 获取服务类别对应的业务类别
						BmsServiceArea main = bmsServiceAreaMapper.selectBmsServiceArea("otherConsultingTechnicalService", string);
						if (main != null && main.getBusiness() != null && !"".equals(main.getBusiness())) {
							String[] resMain = main.getBusiness().split(",");
							for (String string2 : resMain) {
								serviceAreaSet.add(string2);
							}
						}
					}
				}
				if (StringUtils.isNotBlank(bmsProject.getInformationConsultingService())) {
					//信息咨询服务内容
					String[] arr10 = bmsProject.getInformationConsultingService().split(",");
					for (String string : arr10) {
						// 获取服务类别对应的业务类别
						BmsServiceArea main = bmsServiceAreaMapper.selectBmsServiceArea("informationConsultingService", string);
						if (main != null && main.getBusiness() != null && !"".equals(main.getBusiness())) {
							String[] resMain = main.getBusiness().split(",");
							for (String string2 : resMain) {
								serviceAreaSet.add(string2);
							}
						}
					}
				}
				if (StringUtils.isNotBlank(bmsProject.getSpecialConsultingService())) {
					//专项咨询服务内容
					String[] arr11 = bmsProject.getSpecialConsultingService().split(",");
					for (String string : arr11) {
						// 获取服务类别对应的业务类别
						BmsServiceArea main = bmsServiceAreaMapper.selectBmsServiceArea("specialConsultingService", string);
						if (main != null && main.getBusiness() != null && !"".equals(main.getBusiness())) {
							String[] resMain = main.getBusiness().split(",");
							for (String string2 : resMain) {
								serviceAreaSet.add(string2);
							}
						}
					}
				}
				if (StringUtils.isNotBlank(bmsProject.getDesignConsultingService())) {
					//设计咨询服务内容
					String[] arr12 = bmsProject.getDesignConsultingService().split(",");
					for (String string : arr12) {
						// 获取服务类别对应的业务类别
						BmsServiceArea main = bmsServiceAreaMapper.selectBmsServiceArea("designConsultingService", string);
						if (main != null && main.getBusiness() != null && !"".equals(main.getBusiness())) {
							String[] resMain = main.getBusiness().split(",");
							for (String string2 : resMain) {
								serviceAreaSet.add(string2);
							}
						}
					}
				}
			}

		}

		return serviceAreaSet;
	}

	/**
	 * 查询项目列表
	 *
	 * @param bmsProject 项目
	 * @return 项目
	 */
	@Override
	public List<BmsProject> selectBmsProjectList(BmsProject bmsProject) {
		return bmsProjectMapper.selectBmsProjectList(bmsProject);
	}

	/**
	 * 新增项目
	 *
	 * @param bmsProject 项目
	 * @return 结果
	 */
	@Override
	public int insertBmsProject(BmsProject bmsProject) {
		bmsProject.setCreateTime(DateUtils.getNowDate());
		bmsProject.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId());
		if (null == bmsProject.getGuid() || ("").equals(bmsProject.getGuid())) {
			bmsProject.setGuid(UUID.randomUUID().toString());
		}
		return bmsProjectMapper.insertBmsProject(bmsProject);
	}

	/**
	 * 修改项目
	 *
	 * @param bmsProject 项目
	 * @return 结果
	 */
	@Transactional
	@Override
	public int updateBmsProject(BmsProject bmsProject) {
		if (StringUtils.isBlank(bmsProject.getGuid())) {
			return 0;
		}

		BmsProject entity = bmsProjectMapper.selectBmsProjectByGuid(bmsProject.getGuid());

		if(bmsProject.getProjectMain()!=null) {
			bmsProject.setShowProjectMain(bmsProject.getProjectMain().getGuid());
		}else {
			//删除附件
			bmsProject.setShowProjectMain("");
			bmsAttachmentMapper.deleteBmsAttachmentById(entity.getShowProjectMain());
		}

		if(StringUtils.isNotBlank(entity.getAtts())) {
			bmsAttachmentService.deleteBmsAttachmentByIds(entity.getAtts().split(","));
		}

		if(bmsProject.getProjectAttIds()!=null && bmsProject.getProjectAttIds().size()>0) {
			bmsProject.setAtts(StringUtils.join(bmsProject.getProjectAttIds(),","));
		}else {
			bmsProject.setAtts("");
		}

		bmsProject.setUpdateTime(DateUtils.getNowDate());
		bmsProject.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId());
		if (null != bmsProject.getAreas() && bmsProject.getAreas().length > 0) {
			bmsProject.setArea(StringUtils.arrayToString(bmsProject.getAreas()));
		}
		//上传附件，每次删除原来的，添加最新的
		if (StringUtils.isNotBlank(bmsProject.getGuid())) {
			bmsAttachmentMapper.updateBmsAttachmentByBizId(new String[]{bmsProject.getGuid()}, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
		}
		if (!CollectionUtils.isEmpty(bmsProject.getBmsAttachments())) {
			ArrayList<String> attGuids = new ArrayList<String>();
			for (BmsAttachment bmsAttachment : bmsProject.getBmsAttachments()) {
				//biz_id不为null即附件未删除，不存在即新上传的
				if (StringUtils.isBlank(bmsAttachment.getBizId())) {
					attGuids.add(bmsAttachment.getGuid());
				} else {
					BmsAttachment att = new BmsAttachment();
					att.setGuid(bmsAttachment.getGuid());
					att.setDelFlag(NumCode.ZERO.getCode());
					bmsAttachmentMapper.updateBmsAttachment(att);
				}
			}
			if (!CollectionUtils.isEmpty(attGuids)) {
				bmsAttachmentMapper.updateBmsAttachmentByGuidsUpdateBiz(attGuids, bmsProject.getGuid(), AttachmentConstants.PROJECT_PROFILE, tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
			}
		}
		//解析链接
		if (!CollectionUtils.isEmpty(bmsProject.getLinkArray())) {
			String link = "";
			for (Map<String, Object> map : bmsProject.getLinkArray()) {
				Object linkName = map.get("linkName");
				Object linkUrl = map.get("linkUrl");
				if(linkName!=null&&!linkName.equals("")&&linkUrl!=null&&!linkUrl.equals("")){
					link += linkName +","+linkUrl+";";
				}
			}
			bmsProject.setLink(link);
		}
		//所属行业
		if(null!=bmsProject.getIndustrys()&&bmsProject.getIndustrys().length>0){
			bmsProject.setIndustry(StringUtils.arrayToString(bmsProject.getIndustrys()));
		}
		int ret = bmsProjectMapper.updateBmsProjectNew(bmsProject);

		//-------------开始插入历史记录-------------
		insertOper(bmsProject, entity);
		//-------------结束插入历史记录-------------
		if (ret > -1) {
			//插入系统消息
			insertByReceiverUser(bmsProject, entity,true);
		}
		return ret;
	}

	public void insertOper(BmsProject bmsProject,BmsProject entity) {
		BmsProjectShowOper bmsProjectShowOper = new BmsProjectShowOper();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		bmsProjectShowOper.setProjectId(entity.getGuid());
		bmsProjectShowOper.setOperType("2");
		bmsProjectShowOper.setOperPerson(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getNickName());
		bmsProjectShowOper.setOperPersonNo(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getJobNo());
		bmsProjectShowOper.setProjectName(entity.getName());
		bmsProjectShowOper.setProjectCode(entity.getCode());
		bmsProjectShowOper.setProjectLeader(entity.getProjectLeader());
		List<SysDictData> projectStatus = sysDictDataMapper.selectDictDataByType("sys_project_status");
		if(entity.getStatus()!=null&& !entity.getStatus().equals(bmsProject.getStatus())) {
			bmsProjectShowOper.setFieldName("项目进展");
			if(projectStatus !=null && projectStatus.size()>0) {
				for (SysDictData sysDictData : projectStatus) {
					if(sysDictData.getDictValue().equals(entity.getStatus())) {
						bmsProjectShowOper.setInitParams(sysDictData.getDictLabel());
					}
					if(sysDictData.getDictValue().equals(bmsProject.getStatus())) {
						bmsProjectShowOper.setNewParams(sysDictData.getDictLabel());
					}
				}
			}

			bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
		}

		if(entity.getStartDate()!=null &&!entity.getStartDate().equals(bmsProject.getStartDate())) {
			bmsProjectShowOper.setFieldName("开始服务日期");
			bmsProjectShowOper.setInitParams(sdf.format(entity.getStartDate()));
			bmsProjectShowOper.setNewParams(sdf.format(bmsProject.getStartDate()));
			bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
		}

		if(!(entity.getEndDate()==null && bmsProject.getEndDate()==null)) {
			if(bmsProject.getEndDate()!=null && entity.getEndDate()!=null) {
				if(!bmsProject.getEndDate().equals(entity.getEndDate())) {
					bmsProjectShowOper.setFieldName("完成服务日期");
					bmsProjectShowOper.setInitParams(sdf.format(entity.getEndDate()));
					bmsProjectShowOper.setNewParams(sdf.format(bmsProject.getEndDate()));
					bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
				}
			}else {
				if(bmsProject.getEndDate()!=null) {
					if(!bmsProject.getEndDate().equals(entity.getEndDate())) {
						bmsProjectShowOper.setFieldName("完成服务日期");
						bmsProjectShowOper.setInitParams(entity.getEndDate()==null?"":sdf.format(entity.getEndDate()));
						bmsProjectShowOper.setNewParams(sdf.format(bmsProject.getEndDate()));
						bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
					}
				}
				if(entity.getEndDate()!=null) {
					if(!entity.getEndDate().equals(bmsProject.getEndDate())) {
						bmsProjectShowOper.setFieldName("完成服务日期");
						bmsProjectShowOper.setInitParams(sdf.format(entity.getEndDate()));
						bmsProjectShowOper.setNewParams(bmsProject.getEndDate()==null?"":sdf.format(bmsProject.getEndDate()));
						bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
					}
				}
			}
		}


		if(entity.getArea()!=null&& !entity.getArea().equals(bmsProject.getArea())) {
			bmsProjectShowOper.setFieldName("所在地区");
			bmsProjectShowOper.setInitParams(bmsMdAreaMapper.changeName(entity.getArea()));
			bmsProjectShowOper.setNewParams(bmsMdAreaMapper.changeName(bmsProject.getArea()));
			bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
		}

		if(!(StringUtils.isBlank(entity.getAddress()) && StringUtils.isBlank(bmsProject.getAddress()))) {
			if(!entity.getAddress().equals(bmsProject.getAddress())) {
				bmsProjectShowOper.setFieldName("项目地址");
				bmsProjectShowOper.setInitParams(entity.getAddress());
				bmsProjectShowOper.setNewParams(bmsProject.getAddress());
				bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
			}
		}

		if(!(entity.getInvestment()==null && bmsProject.getInvestment()==null)) {
			if(bmsProject.getInvestment()!=null && entity.getInvestment()!=null) {
				if(Double.doubleToLongBits(bmsProject.getInvestment())!=Double.doubleToLongBits(entity.getInvestment())) {
					bmsProjectShowOper.setFieldName("项目总投资(万元)");
					bmsProjectShowOper.setInitParams(entity.getInvestment().toString());
					bmsProjectShowOper.setNewParams(bmsProject.getInvestment().toString());
					bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
				}
			}else {
				if(bmsProject.getInvestment()!=null) {
					bmsProjectShowOper.setFieldName("项目总投资(万元)");
					bmsProjectShowOper.setInitParams("");
					bmsProjectShowOper.setNewParams(bmsProject.getInvestment().toString());
					bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
				}
				if(entity.getInvestment()!=null) {
					bmsProjectShowOper.setFieldName("项目总投资(万元)");
					bmsProjectShowOper.setInitParams(entity.getInvestment().toString());
					bmsProjectShowOper.setNewParams("");
					bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
				}
			}
		}

		if(!(StringUtils.isBlank(entity.getIndustry()) && StringUtils.isBlank(bmsProject.getIndustry()))) {
			if(!entity.getIndustry().equals(bmsProject.getIndustry())) {
				bmsProjectShowOper.setFieldName("所属行业");
				bmsProjectShowOper.setInitParams(bmsMdIndustryCategoryMapper.changeName(entity.getIndustry()) );
				bmsProjectShowOper.setNewParams(bmsMdIndustryCategoryMapper.changeName(bmsProject.getIndustry()) );
				bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
			}
		}

		if(!(StringUtils.isBlank(entity.getConstructionType()) && StringUtils.isBlank(bmsProject.getConstructionType()))) {
			if(!bmsProject.getConstructionType().equals(entity.getConstructionType())) {
				bmsProjectShowOper.setFieldName("建设类型");
				if("".equals(entity.getConstructionType())) {
					bmsProjectShowOper.setInitParams("");
				}else {
					bmsProjectShowOper.setInitParams("0".equals(entity.getConstructionType())?"新建":"改扩建");
				}
				if("".equals(bmsProject.getConstructionType())) {
					bmsProjectShowOper.setNewParams("");
				}else {
					bmsProjectShowOper.setNewParams("0".equals(bmsProject.getConstructionType())?"新建":"改扩建");
				}


				bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
			}
		}

		if(!(StringUtils.isBlank(entity.getContent()) && StringUtils.isBlank(bmsProject.getContent()))) {
			if(!entity.getContent().equals(bmsProject.getContent())) {
				bmsProjectShowOper.setFieldName("建设内容及规模");
				bmsProjectShowOper.setInitParams(entity.getContent());
				bmsProjectShowOper.setNewParams(bmsProject.getContent());
				bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
			}
		}

		if(!(StringUtils.isBlank(entity.getMainServiceContent()) && StringUtils.isBlank(bmsProject.getMainServiceContent()))) {
			if(!entity.getMainServiceContent().equals(bmsProject.getMainServiceContent())) {
				bmsProjectShowOper.setFieldName("服务内容");
				bmsProjectShowOper.setInitParams(entity.getMainServiceContent());
				bmsProjectShowOper.setNewParams(bmsProject.getMainServiceContent());
				bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
			}
		}

		if(!(StringUtils.isBlank(entity.getShowProject()) && StringUtils.isBlank(bmsProject.getShowProject()))) {
			if(!entity.getShowProject().equals(bmsProject.getShowProject())) {
				bmsProjectShowOper.setFieldName("是否启用项目展示");
				if("".equals(entity.getShowProject())) {
					bmsProjectShowOper.setInitParams("");
				}else {
					bmsProjectShowOper.setInitParams("0".equals(entity.getShowProject())?"否":"是");
				}

				if("".equals(bmsProject.getShowProject())) {
					bmsProjectShowOper.setNewParams("");
				}else {
					bmsProjectShowOper.setNewParams("0".equals(bmsProject.getShowProject())?"否":"是");
				}


				bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
			}
		}

		if(!(StringUtils.isBlank(entity.getIsSecurity()) && StringUtils.isBlank(bmsProject.getIsSecurity()))) {
			if(!entity.getIsSecurity().equals(bmsProject.getIsSecurity())) {
				bmsProjectShowOper.setFieldName("是否保密工程");
				if("".equals(entity.getIsSecurity())) {
					bmsProjectShowOper.setInitParams("");
				}else {
					bmsProjectShowOper.setInitParams("0".equals(entity.getIsSecurity())?"否":"是");
				}

				if("".equals(bmsProject.getIsSecurity())) {
					bmsProjectShowOper.setNewParams("");
				}else {
					bmsProjectShowOper.setNewParams("0".equals(bmsProject.getIsSecurity())?"否":"是");
				}

				bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
			}
		}

		if(!(StringUtils.isBlank(entity.getIsShare()) && StringUtils.isBlank(bmsProject.getIsShare()))) {
			if(!entity.getIsShare().equals(bmsProject.getIsShare())) {
				bmsProjectShowOper.setFieldName("是否分享");
				if("0".equals(entity.getIsShare())) {
					bmsProjectShowOper.setInitParams("不分享");
				}else if("1".equals(entity.getIsShare())) {
					bmsProjectShowOper.setInitParams("完整分析");
				}else if("2".equals(entity.getIsShare())) {
					bmsProjectShowOper.setInitParams("部分分享");
				}else {
					bmsProjectShowOper.setInitParams("");
				}

				if("0".equals(bmsProject.getIsShare())) {
					bmsProjectShowOper.setInitParams("不分享");
				}else if("1".equals(bmsProject.getIsShare())) {
					bmsProjectShowOper.setInitParams("完整分析");
				}else if("2".equals(bmsProject.getIsShare())) {
					bmsProjectShowOper.setInitParams("部分分享");
				}else {
					bmsProjectShowOper.setInitParams("");
				}
				bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
			}
		}

		if(!(StringUtils.isBlank(entity.getShowProjectName()) && StringUtils.isBlank(bmsProject.getShowProjectName()))) {
			if(!entity.getShowProjectName().equals(bmsProject.getShowProjectName())) {
				bmsProjectShowOper.setFieldName("展示项目名称");
				bmsProjectShowOper.setInitParams(entity.getShowProjectName());
				bmsProjectShowOper.setNewParams(bmsProject.getShowProjectName());
				bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
			}
		}

		if(!(StringUtils.isBlank(entity.getShowProjectMember()) && StringUtils.isBlank(bmsProject.getShowProjectMember()))) {
			if(!entity.getShowProjectMember().equals(bmsProject.getShowProjectMember())) {
				bmsProjectShowOper.setFieldName("展示项目团队");
				bmsProjectShowOper.setInitParams(entity.getShowProjectMember());
				bmsProjectShowOper.setNewParams(bmsProject.getShowProjectMember());
				bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
			}
		}

		if (!CollectionUtils.isEmpty(bmsProject.getLinkArray())) {
			String link = "";
			for (Map<String, Object> map : bmsProject.getLinkArray()) {
				Object linkName = map.get("linkName");
				Object linkUrl = map.get("linkUrl");
				if(linkName!=null&&!linkName.equals("")&&linkUrl!=null&&!linkUrl.equals("")){
					link += linkName +","+linkUrl+";";
				}
			}
			bmsProject.setLink(link);
		}

		if(!(StringUtils.isBlank(entity.getLink()) && StringUtils.isBlank(bmsProject.getLink()))) {
			if(!entity.getLink().equals(bmsProject.getLink())) {
				bmsProjectShowOper.setFieldName("相关链接");
				bmsProjectShowOper.setInitParams(entity.getLink());
				bmsProjectShowOper.setNewParams(bmsProject.getLink());
				bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
			}
		}

    	/*if(!(StringUtils.isBlank(entity.getLonLat()) && StringUtils.isBlank(bmsProject.getLonLat()))) {
    		if(!bmsProject.getLonLat().equals(entity.getLonLat())) {
    			bmsProjectShowOper.setFieldName("地图经纬度");
        		bmsProjectShowOper.setInitParams(entity.getLonLat());
        		bmsProjectShowOper.setNewParams(bmsProject.getLonLat());
        		bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
    		}
    	}*/

		if(!(StringUtils.isBlank(entity.getProjectDesc()) && StringUtils.isBlank(bmsProject.getProjectDesc()))) {
			if(!entity.getProjectDesc().equals(bmsProject.getProjectDesc())) {
				bmsProjectShowOper.setFieldName("项目概况描述");
				bmsProjectShowOper.setInitParams(entity.getProjectDesc());
				bmsProjectShowOper.setNewParams(bmsProject.getProjectDesc());
				bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
			}
		}

		if(!(StringUtils.isBlank(entity.getSpecEffect()) && StringUtils.isBlank(bmsProject.getSpecEffect()))) {
			if(!entity.getSpecEffect().equals(bmsProject.getSpecEffect())) {
				bmsProjectShowOper.setFieldName("项目特点与成效");
				bmsProjectShowOper.setInitParams(entity.getSpecEffect());
				bmsProjectShowOper.setNewParams(bmsProject.getSpecEffect());
				bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
			}
		}

		if(!(StringUtils.isBlank(entity.getShowHonor()) && StringUtils.isBlank(bmsProject.getShowHonor()))) {
			if(!entity.getShowHonor().equals(bmsProject.getShowHonor())) {
				bmsProjectShowOper.setFieldName("项目所获荣誉");
				bmsProjectShowOper.setInitParams(entity.getShowHonor());
				bmsProjectShowOper.setNewParams(bmsProject.getShowHonor());
				bmsProjectShowOperService.insertBmsProjectShowOper(bmsProjectShowOper);
			}
		}


	}

	/**
	 * 插入系统消息
	 *
	 * @param bmsProject
	 */
	private void insertByReceiverUser(BmsProject bmsProject,BmsProject entity,Boolean type) {

		if (null != entity && StringUtils.isNotBlank(bmsProject.getFreezeStatus()) && !entity.getFreezeStatus().equals(bmsProject.getFreezeStatus())) {
			SysUser updateUser = iSysUserService.selectUserById(bmsProject.getUpdateBy());
			SysUser sysUser = new SysUser();
			String freezeStatus = bmsProject.getFreezeStatus();
			//消息类型
			String msgType = "";
			//消息内容
			String content  = "";
			if(null != updateUser){
				content += StringUtils.isNotBlank(updateUser.getNickName())? updateUser.getNickName() : updateUser.getUserName();
				content += "：“";
			}else{
				content += "“";
			}
			content += StringUtils.isBlank(entity.getName()) ? entity.getGuid() : entity.getName();

			if (NumCode.ZERO.getCode().equals(freezeStatus)) {
				msgType = "项目冻结";
				content += "项目已被冻结，请关注。”";
			} else if (NumCode.ONE.getCode().equals(freezeStatus)) {
				msgType = "项目解冻";
				content += "项目已被解冻，请关注。”";
			}
			//项目负责人
			String userGuid = "";
			if (StringUtils.isNotBlank(entity.getUserGlobalId())) {
				sysUser.setGlobalId(entity.getUserGlobalId());
				SysUser projectLeader = iSysUserService.selectUserByUser(sysUser);
				if (null != projectLeader ) {
					userGuid = projectLeader.getUserId();
					iBmsMsgService.insertByReceiverUser(userGuid, msgType, content,type);
				}
			}
			//项目经理  与项目负责人为同一个人，只发送一条消息提醒
			if (StringUtils.isNotBlank(entity.getProjectManager()) && !userGuid.equals(entity.getProjectManager())) {
				iBmsMsgService.insertByReceiverUser(entity.getProjectManager(), msgType, content,type);
			}

		}
	}

	/**
	 * 批量删除项目
	 *
	 * @param guids 需要删除的项目guid
	 * @return 结果
	 */
	@Override
	public int deleteBmsProjectByGuids(String[] guids) {
		return bmsProjectMapper.deleteBmsProjectByGuids(guids);
	}

	/**
	 * 删除项目信息
	 *
	 * @param id 项目ID
	 * @return 结果
	 */
	@Override
	public int deleteBmsProjectByGuid(String id) {
		return bmsProjectMapper.deleteBmsProjectByGuid(id);
	}

	/**
	 * @param projectLeader 项目负责人
	 * @return
	 */
//    @Override
//    public List<BmsProject> selectBmsProjectByProjectLeader(String projectLeader) {
//        return bmsProjectMapper.selectBmsProjectByProjectLeader(projectLeader);
//    }

	/**
	 * @param bmsProject 项目
	 * @return
	 */
	@Override
	public List<BmsProjectSimple> selectBmsProjectGlanceList(BmsProjectSimple bmsProject) {
		return bmsProjectMapper.selectBmsProjectGlanceList(bmsProject);
	}

	@Override
	public BmsProject selectBmsProjectById(String guid) {
		return bmsProjectMapper.selectBmsProjectById(guid);
	}

	@Override
	public AjaxResult updateBmsProjectByThirdParty(String userGuid, Boolean allUpdates,Boolean type) {
		try {
			log.info(" 项目信息定时任务执行:"+ (new Date()));
			List<BmsProject> list = bmsProjectSynchronous(userGuid);
			inserOrUpdateThirdData(list, allUpdates,type);
		} catch (Exception e) {
			log.error("项目同步失败，详细信息："+e);
			e.printStackTrace();
		}
		return AjaxResult.success();
	}

	/**
	 * 获取项目同步数据
	 * @param userGuid
	 * @return
	 */
	private List<BmsProject> bmsProjectSynchronous(String userGuid){
		List<BmsProject> list = new ArrayList<>();
		if (StringUtils.isNotBlank(userGuid)) {
			BmsProject bmsProject = bmsProjectMapper.selectBmsProjectByUserGuid(userGuid);
			if(null != bmsProject ){
				if (StringUtils.isNotBlank(bmsProject.getProjectLeader()) && StringUtils.isNotBlank(bmsProject.getProjectLeaderNo())) {
					//第三方接口接入后，打开
					long max=bmsProjectMapper.selectMaxTimeLeaderNo(bmsProject.getProjectLeaderNo());
					list = this.synchronous(bmsProject.getProjectLeader(), bmsProject.getProjectLeaderNo(), max);
					//list = getdata(bmsProject.getProjectLeader(), bmsProject.getProjectLeaderNo(),bmsProjectMapper.selectMaxTime());
				}
			}else{
				BmsProjectLeader bmsProjectLeader = bmsProjectLeaderMapper.selectBmsProjectLeaderByUserId(userGuid);
				if(null!=bmsProjectLeader&&StringUtils.isNotBlank(bmsProjectLeader.getUserName()) && StringUtils.isNotBlank(bmsProjectLeader.getLeadNo())){
					list = this.synchronous(bmsProjectLeader.getUserName(), bmsProjectLeader.getLeadNo(), 0);
				}
			}
		} else {
			//第三方接口接入后，打开
			//list = this.synchronous("", "", bmsProjectMapper.selectMaxTime());
			list = this.synchronous("", "", bmsProjectMapper.selectMaxTime());
			// list =  getdata("", "",bmsProjectMapper.getMaxTimeStamp());
		}
		return list ;
	}

	/**
	 * 处理获取到的项目同步数据
	 * @param list
	 * @param allUpdates
	 */
	private void inserOrUpdateThirdData(List<BmsProject> list, Boolean allUpdates,Boolean type){
		if (!CollectionUtils.isEmpty(list)) {
			//按项目负责人同步时，不更新时间戳
			if (!allUpdates) {
				list.forEach(entity -> {
					entity.setTimeStamp("");
				});
			}
			//获取数据库得所有global_id
			List<BmsProject> allList = bmsProjectMapper.selectBmsProjectList(new BmsProject());
			List<String> globalIdList = allList.stream().map(k -> k.getGlobalId()).collect(Collectors.toList());


			//插入第三方数据
			insertThirdData(list, globalIdList);
			//更新第三方数据,
			updateThirdData(list, allList, globalIdList,type);
		}
	}

	/**
	 * 项目概要页面“获取经营系统最新数据”
	 * @param oldBmsProject       项目
	 * @return
	 */
	@Transactional
	@Override
	public AjaxResult updateBmsProjectByThirdParty(BmsProject oldBmsProject) {
		if (oldBmsProject!=null&&StringUtils.isNotBlank(oldBmsProject.getGlobalId())) {
			try {
				//第三方接口接入后，打开
				//强制更新默认设置为0，上线恢复取最大值
				List<Map<String, Object>> projectMap = projectDao.getProjectList("","", oldBmsProject.getGlobalId(), selectMaxTime());
				List<BmsProjectLeader> bmsProjectLeaderList = iBmsProjectLeaderService.selectBmsProjectLeaderList(new BmsProjectLeader());
				Map<String, String> bmsProjectLeadermap = bmsProjectLeaderList.stream().filter(t -> t.getUserGlobalid() != null).collect(Collectors.toMap(BmsProjectLeader::getLeadNo, BmsProjectLeader::getUserGlobalid, (k1, k2) -> k1));
				List<BmsProject> list = dealWith(projectMap, bmsProjectLeadermap);
				inserOrUpdateThirdData(list, false,true);
			} catch (Exception e) {
				log.error("項目概況获取经营系统最新数据失败，详细信息："+e);
				e.printStackTrace();
			}
		}
		return AjaxResult.success();
	}

	/**
	 * 更新第三方数据
	 *
	 * @param list
	 * @param allList
	 * @param globalIdList
	 */
	private void updateThirdData(List<BmsProject> list, List<BmsProject> allList, List<String> globalIdList,Boolean type){
		Date time = DateUtils.getNowDate();
		//        String user = SecurityUtils.getLoginUser().getUser().getUserId();
		//要更新的数据
		List<BmsProject> updateList = list.stream().filter(item -> globalIdList.contains(item.getGlobalId())).collect(Collectors.toList());
		//处理update的数据
		Map<String, List<BmsProject>> updateMap = allList.stream().collect(Collectors.groupingBy(BmsProject::getGlobalId));
		for (BmsProject item : updateList) {
			try {
				//判断是否更新流程标识
				Boolean updateFlow = false;
				item.setUpdateTime(time);
				//            item.setUpdateBy(user);

				BmsProject bmsProject = updateMap.get(item.getGlobalId()).get(0);
				//所在公司不是“同济咨询”[自动冻结此项目,改项目冻结字段为“已冻结”}
				if (!ObjectUtils.nullSafeEquals("同济咨询", item.getProjectCompany())) {
					//                item.setIsvalid(NumCode.ZERO.getCode());
					item.setFreezeStatus(NumCode.ZERO.getCode());
					updateFlow = true;
				}
				//数据有效性变动,已第三方数据为准
				if (!ObjectUtils.nullSafeEquals(bmsProject.getIsvalid(),item.getIsvalid()) && ObjectUtils.nullSafeEquals(NumCode.ZERO.getCode(), item.getIsvalid())) {
					updateFlow = true;
					item.setFreezeStatus(NumCode.ZERO.getCode());
					//进行消息推送
					insertByReceiverUser(item, bmsProject,type);
				}
				//当项目已启动的时候，状态已本系统为准;如果项目实施状态变成“项目作废”，则更新状态，不然不更新
				if (ObjectUtils.nullSafeEquals(NumCode.ZERO.getCode(), bmsProject.getEnableFlag())||!ObjectUtils.nullSafeEquals(ProjectStatus.cancellation, bmsProject.getStatus())) {
					item.setStatus("");
				}
				//当项目未启用，地区不同
				if (ObjectUtils.nullSafeEquals(NumCode.ONE.getCode(), bmsProject.getEnableFlag()) && !ObjectUtils.nullSafeEquals(bmsProject.getArea(),item.getArea())) {
					item.setArea(item.getArea());
				}
				//当项目已启动的时候,不更新项目总投资_万元
				if (ObjectUtils.nullSafeEquals(NumCode.ZERO.getCode(), bmsProject.getEnableFlag())){
					item.setInvestment(null);
					item.setStartDate(null);
					item.setArea(null);
					item.setContent(null);
					item.setMainServiceContent(null);

				}

                    /*if(StringUtils.isNotBlank(bmsProject.getContent())) {
                    	item.setContent(null);
                    }

                    if(StringUtils.isNotBlank(bmsProject.getMainServiceContent())) {
                    	item.setMainServiceContent(null);
                    }*/
				//执行部门变化
				if (!ObjectUtils.nullSafeEquals(bmsProject.getExecuteDept(), item.getExecuteDept())) {
					updateFlow = true;
				}
				//项目负责人代码变化
				if (!ObjectUtils.nullSafeEquals(bmsProject.getProjectLeaderNo(), item.getProjectLeaderNo()) && !ObjectUtils.nullSafeEquals(bmsProject.getUserGlobalId(), item.getUserGlobalId())) {
					//处理项目负责人代码变化
					disposeProjectLeaderNo(item, bmsProject);
					//调bpm接口
					updateFlow = true;
				}

				bmsProjectMapper.updateBmsProjectByGlobalId(item);
				//调bpm接口，将项目所有业务中未完成流程在BPM中终止（取消）
				if(updateFlow){
					BmsWorkflow bmsWorkflow = new BmsWorkflow();
					bmsWorkflow.setProjectId(bmsProject.getGuid());
					cancelInstance(bmsWorkflow);
				}
			} catch (Exception e) {
				log.error("修改项目同步数据处理失败，详细信息："+e);
				e.printStackTrace();
			}
		}

	}

	/**
	 * 项目负责人代码变化
	 *
	 * @param item
	 * @param bmsProject
	 */
	private void disposeProjectLeaderNo(BmsProject item, BmsProject bmsProject){
		try {
			if (StringUtils.isNotBlank(item.getUserGlobalId())) {
				//去查用户表的信息
				SysUser sysUser = new SysUser();
				//老的负责人
				sysUser.setGlobalId(bmsProject.getUserGlobalId());
				SysUser oldLeaderSysUser = iSysUserService.selectUserByUser(sysUser);
				//移除项目的关注
				if (null != oldLeaderSysUser && StringUtils.isNotBlank(oldLeaderSysUser.getUserId()) && StringUtils.isNotBlank(bmsProject.getGuid())) {
					iBmsProjectFocusService.deleteBmsProjectFocusByUserAndProject(oldLeaderSysUser.getUserId(), bmsProject.getGuid());
				}
				//新的负责人
				sysUser.setGlobalId(item.getUserGlobalId());
				SysUser leaderSysUser = iSysUserService.selectUserByUser(sysUser);

				if (null != leaderSysUser && StringUtils.isNotBlank(bmsProject.getGuid())) {
					BmsLeaderMember bmsLeaderMember = new BmsLeaderMember();
					//设置新的项目负责人
					bmsLeaderMember.setLeader(leaderSysUser.getUserId());
					//项目下面的成员
					BmsProjectMember bmsProjectMember = new BmsProjectMember();
					bmsProjectMember.setProjectId(bmsProject.getGuid());
					List<BmsProjectMember> bmsProjectMemberList = iBmsProjectMemberService.selectNotInBmsProjectMemberList(bmsProjectMember, leaderSysUser.getUserId());
					bmsProjectMemberList.forEach(it -> {
						//过滤掉项目成员中包含的原项目负责人
						if(!ObjectUtils.nullSafeEquals(oldLeaderSysUser.getUserId(), it.getUserId())){
							bmsLeaderMember.setUserId(it.getUserId());
							//默认设置为成员
							bmsLeaderMember.setRole("0");
							bmsLeaderMember.setRemark("项目负责人变更，系统自动插入");
							bmsLeaderMember.setGuid(UUID.randomUUID().toString());
							bmsLeaderMemberMapper.insertBmsLeaderMember(bmsLeaderMember);
						}
					});

				}
			}
		} catch (Exception e) {
			log.error("项目负责人代码变化处理失败，详细信息："+e);
			e.printStackTrace();
		}
	}

	/**
	 * 插入第三方数据
	 *
	 * @param list
	 * @param globalIdList
	 */
	private void insertThirdData(List<BmsProject> list, List<String> globalIdList){
		try {
			//要插入的数据
			List<BmsProject> insertList = list.stream().filter(item -> !globalIdList.contains(item.getGlobalId())&&"同济咨询".equals(item.getProjectCompany())).collect(Collectors.toList());
			int size = insertList.size();
			//分页插入数据
			int times = size / INSERT_BATCH_DIVISOR;
			int remain = size % INSERT_BATCH_DIVISOR;
			//完整一页
			for (int i = 0; i < times; i++) {
				List<BmsProject> subList = insertList.subList(i * INSERT_BATCH_DIVISOR, (i + 1) * INSERT_BATCH_DIVISOR);
				bmsProjectMapper.batchInsertBmsProject(subList);
			}
			//剩余部分
			if (remain > 0) {
				List<BmsProject> subList = insertList.subList(INSERT_BATCH_DIVISOR * times, insertList.size());
				bmsProjectMapper.batchInsertBmsProject(subList);
			}
		} catch (Exception e) {
			log.error("添加项目同步数据处理失败，详细信息："+e);
			e.printStackTrace();
		}
	}

	//接口模拟数据
	private List<BmsProject> getdata(String projectLeader, String projectLeaderNo, String time) {
		List<BmsProject> list = new ArrayList<>();
		BmsProject bmsProject1 = new BmsProject();
		BmsProject bmsProject2 = new BmsProject();
		BmsProject bmsProject3 = new BmsProject();
		BmsProject bmsProject4 = new BmsProject();

		bmsProject1.setGlobalId("3");
		bmsProject1.setCode("3");
		bmsProject1.setName("3");
		bmsProject1.setStatus("3");
		bmsProject1.setStartDate(new Date());
		bmsProject1.setExecuteDept("3");
		bmsProject1.setProjectCompany("3");
		bmsProject1.setProjectLeader("3");
		bmsProject1.setProjectLeaderNo("3");
		bmsProject1.setUserGlobalId("103");
		bmsProject1.setParty("3");
		//bmsProject1.setInvestment(3l);
		bmsProject1.setIsvalid("3");
		bmsProject1.setTimeStamp("333333333333333333333333");
		list.add(bmsProject1);
		bmsProject2.setGlobalId("5");
		bmsProject2.setCode("5");
		bmsProject2.setName("5");
		bmsProject2.setStatus("5");
		bmsProject2.setIsvalid("5");
		bmsProject2.setExecuteDept("5");
		bmsProject2.setProjectLeaderNo("5");
		bmsProject2.setUserGlobalId("103");
		list.add(bmsProject2);
		bmsProject3.setGlobalId("6");
		bmsProject3.setCode("6");
		bmsProject3.setName("6");
		bmsProject3.setStatus("6");
		bmsProject3.setIsvalid("6");
		bmsProject3.setExecuteDept("6");
		bmsProject3.setProjectLeaderNo("6");
		bmsProject3.setUserGlobalId("103");
		list.add(bmsProject3);
		bmsProject4.setGlobalId("7");
		bmsProject4.setCode("7");
		bmsProject4.setName("7");
		bmsProject4.setStatus("7");
		bmsProject4.setIsvalid("7");
		bmsProject4.setExecuteDept("7");
		bmsProject4.setProjectLeaderNo("7");
		bmsProject4.setUserGlobalId("103");
		list.add(bmsProject4);
		return list;
	}

	/**
	 * @return List<BmsProjectSimple>
	 * @describe  同步项目数据
	 * @params [leder, date] leder 项目负责人id date 时间戳
	 * @author VillWang
	 * @date 2020/5/21
	 * @other
	 */
	@Override
	public List<BmsProject> synchronous(String leder, String projectLeaderNo, long max) {
		List<Map<String,Object>> masonDepartmentList=projectDao.getProjectList(leder,projectLeaderNo,"",max);

		//获取负责人数据
		List<BmsProjectLeader> bmsProjectLeaderList = iBmsProjectLeaderService.selectBmsProjectLeaderList(new BmsProjectLeader());
		Map<String, String> bmsProjectLeadermap = bmsProjectLeaderList.stream().filter(t -> t.getUserGlobalid() != null).collect(Collectors.toMap(BmsProjectLeader::getLeadNo, BmsProjectLeader::getUserGlobalid, (k1, k2) -> k1));
		List<BmsProject> list = dealWith(masonDepartmentList, bmsProjectLeadermap);
		return list;
	}

	/**
	 * 我的项目(总项目数、进行中项目数、筹备中项目数)
	 *
	 * @return
	 */
	@Override
	public Map<String, Object> countMyProject(String userGuid) {
		if (StringUtils.isBlank(userGuid)) {
			return null;
		}
		Map<String, Object> map = new HashMap<>();
		Set<String> projectLeaderSet = new HashSet<>();
		Set<String> projectMemberSet = new HashSet<>();
		BmsProjectMember bmsProjectMember = new BmsProjectMember();
		bmsProjectMember.setUserId(userGuid);
		String projectLeaderNo = sysUserService.findProjectLeaderNoByUserGuid(userGuid);

		bmsProjectMember.setProjectStatus(ProjectStatus.MAKE_PREPARATIONS);//筹备期
//        int projectLeaderCount = 0;
		if(StringUtils.isNotBlank(projectLeaderNo)){
			projectLeaderSet = bmsProjectMapper.selectBmsProjectLeaderByUserIdOrProjectStatus(projectLeaderNo, ProjectStatus.MAKE_PREPARATIONS);
		}
		projectMemberSet = bmsProjectMemberService.selectBmsProjectMemberByUserIdOrProjectStatus(bmsProjectMember);
		projectMemberSet.addAll(projectLeaderSet);
		map.put("preparationNo", projectMemberSet.size());

		bmsProjectMember.setProjectStatus(ProjectStatus.UNDERWAY);//进行中
		if(StringUtils.isNotBlank(projectLeaderNo)){
			projectLeaderSet = bmsProjectMapper.selectBmsProjectLeaderByUserIdOrProjectStatus(projectLeaderNo, ProjectStatus.UNDERWAY);
		}
		projectMemberSet = bmsProjectMemberService.selectBmsProjectMemberByUserIdOrProjectStatus(bmsProjectMember);
		projectMemberSet.addAll(projectLeaderSet);
		map.put("processingNo", projectMemberSet.size());

		bmsProjectMember.setProjectStatus(ProjectStatus.DELIVERY);//成果交付
//        projectLeaderCount = 0;
		if(StringUtils.isNotBlank(projectLeaderNo)){
			projectLeaderSet = bmsProjectMapper.selectBmsProjectLeaderByUserIdOrProjectStatus(projectLeaderNo, ProjectStatus.DELIVERY);
		}
		projectMemberSet = bmsProjectMemberService.selectBmsProjectMemberByUserIdOrProjectStatus(bmsProjectMember);
		projectMemberSet.addAll(projectLeaderSet);
		map.put("deliveryNo", projectMemberSet.size());

		bmsProjectMember.setProjectStatus(null);//总数
//        projectLeaderCount = 0;
		if(StringUtils.isNotBlank(projectLeaderNo)){
			projectLeaderSet = bmsProjectMapper.selectBmsProjectLeaderByUserIdOrProjectStatus(projectLeaderNo, null);
		}
		projectMemberSet = bmsProjectMemberService.selectBmsProjectMemberByUserIdOrProjectStatus(bmsProjectMember);
		projectMemberSet.addAll(projectLeaderSet);
		map.put("totalNo", projectMemberSet.size());
		return map;
	}
	/**
	 *
	 *@describe  获取最大时间戳
	 *@params []
	 *@return java.lang.String
	 *@author VillWang
	 *@date 2020/6/11
	 *@other
	 *
	 */
	@Override
	public long selectMaxTime() {
		long max= bmsProjectMapper.selectMaxTime();
		return max;
	}

	/**
	 * 修改项目负责人代码通过项目负责人Guid
	 * @param projectLeader 项目负责人Guid
	 * @param projectLeaderNo 项目负责人代码
	 * @return
	 */
	@Override
	public int updateBmsProjectLeaderNoByProjectLeader(String projectLeader, String projectLeaderNo) {
		return bmsProjectMapper.updateBmsProjectLeaderNoByProjectLeader(projectLeader, projectLeaderNo);
	}

	/**
	 * 修改项目项目经理
	 * @param projectId 项目Id
	 * @param projectManager 项目经理用户id
	 * @return
	 */
	@Override
	public int updateBmsProjectManager(String projectId, String projectManager) {
		return bmsProjectMapper.updateBmsProjectManager(projectId, projectManager);
	}

	/**
	 * 同步获取并处理项目负责人的项目合同数据
	 * @param userGuid
	 */
	@Override
	public void updateBmsProjectContractByThirdParty(String userGuid) {
		try {
			List<BmsProject> list = bmsProjectSynchronous(userGuid);
			for (BmsProject bmsProject : list) {
				bmsProjectContractService.synchronous(bmsProject.getCode(),bmsProjectContractService.selectMaxTime());
			}
		} catch (Exception e) {
			log.error("项目负责人工作台同步未加入项目、项目合同数据失败，详细信息："+e);
			e.printStackTrace();
		}
	}

	/**
	 * @return java.util.List<com.tjec.project.mdmSynchronous.domain.SysAdministrative>
	 * @describe 处理返回的json数据
	 * @params []
	 * @author VillWang
	 * @date 2020/5/14
	 * @other
	 */
	public List<BmsProject> dealWith(List<Map<String,Object>> maps, Map<String, String> bmsProjectLeadermap) {
		//从数据获取模拟数据
        /*List<BmsProject> BmsProjectList = bmsProjectMapper.getSimulatedData();
        BmsProjectList.forEach(item -> {
            item.setUserGlobalId(bmsProjectLeadermap.get(item.getProjectLeaderNo()));
        });*/
		//待验证
		List<BmsProject> BmsProjectList = new ArrayList<BmsProject>();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			for (Map<String, Object> map : maps) {
				BmsProject bmsProject = new BmsProject();
				bmsProject.setGlobalId((String) map.get("projectGlobalId"));
				//项目全局ID默认转大写
				bmsProject.setGlobalId(bmsProject.getGlobalId().toUpperCase());
				bmsProject.setName((String) map.get("name"));
				bmsProject.setCode((String) map.get("code"));
				String state=(String) map.get("status");
				if(StringUtils.isNotBlank(state)){
					if(state.equals("项目完成")){
						bmsProject.setStatus(ProjectStatus.COMPLETE);
					}else if(state.equals("项目终止")){
						bmsProject.setStatus(ProjectStatus.TERMINATION);
					}else if(state.equals("成果交付")){
						bmsProject.setStatus(ProjectStatus.DELIVERY);
					}else if(state.equals("进行中")){
						bmsProject.setStatus(ProjectStatus.UNDERWAY);
					}else if(state.equals("项目暂停")){
						bmsProject.setStatus(ProjectStatus.PAUSE);
					}else if(state.equals("筹备")){
						bmsProject.setStatus(ProjectStatus.MAKE_PREPARATIONS);
					}else if(state.equals("项目作废")){
                        bmsProject.setStatus(ProjectStatus.cancellation);
                    }else {
						log.info("项目状态为 - {}", state);
					}
				}else {
					bmsProject.setStatus(ProjectStatus.cancellation);
				}
				String date = (String) map.get("startDate");
				if (StringUtils.isNotBlank(date)) {
					bmsProject.setStartDate(sdf.parse(date));
				}
				bmsProject.setExecuteDept((String) map.get("executeDept"));
				bmsProject.setProjectCompany((String) map.get("projectCompany"));
				bmsProject.setProjectLeader((String) map.get("projectLeader"));
				String projectLeaderNo = (String) map.get("projectLeaderNo");
				if (StringUtils.isNotBlank(projectLeaderNo)) {
					bmsProject.setUserGlobalId(bmsProjectLeadermap.get(projectLeaderNo));
				}
				bmsProject.setProjectLeaderNo(projectLeaderNo);
				bmsProject.setParty((String) map.get("party"));
				bmsProject.setBuildUnit((String) map.get("party"));
				bmsProject.setInvestment((Double) map.get("investment"));
				//数据有效性设置默认值
				String isValid = (String) map.get("isValid");
				if (StringUtils.isBlank(isValid)) {
					isValid = NumCode.ONE.getCode();
				}
				if ("有效".equals(isValid)) {
					isValid = NumCode.ONE.getCode();
				} else {
					isValid = NumCode.ZERO.getCode();
				}
				bmsProject.setIsvalid(isValid);
				bmsProject.setTimeStamp(String.valueOf(map.get("timestamp")));
				//服务类别
				bmsProject.setServiceType((String) map.get("serviceType"));
				//工程咨询服务内容
				bmsProject.setEngineeringConsultingService((String) map.get("engineeringConsultingService"));
				//招标代理服务内容
				bmsProject.setBiddingAgencyService((String) map.get("biddingAgencyService"));
				//造价咨询服务内容
				bmsProject.setCostConsultingService((String) map.get("costConsultingService"));
				//项目管理服务内容
				bmsProject.setProjectManagementService((String) map.get("projectManagementService"));
				//工程监理服务内容
				bmsProject.setProjectSupervisionService((String) map.get("projectSupervisionService"));
				//设备监理服务内容
				bmsProject.setEquipmentSupervisionService((String) map.get("equipmentSupervisionService"));
				//检测服务服务内容
				bmsProject.setTestingService((String) map.get("testingService"));
				//环评资质服务内容
				bmsProject.setEiaQualificationService((String) map.get("eiaQualificationService"));
				//其他咨询与技术服务内容
				bmsProject.setOtherConsultingTechnicalService((String) map.get("otherConsultingTechnicalService"));
				//结项情况
				bmsProject.setClosureSituation((String) map.get("closureSituation"));
				bmsProject.setInformationConsultingService((String) map.get("informationConsultingService"));
				bmsProject.setSpecialConsultingService((String) map.get("specialConsultingService"));
				bmsProject.setDesignConsultingService((String) map.get("designConsultingService"));
				bmsProject.setMainServiceContent((String) map.get("mainServiceContent"));
				bmsProject.setContent((String) map.get("content"));
				//地区
				String area = areaTransform((String) map.get("area"));
				bmsProject.setArea(area);
				BmsProjectList.add(bmsProject);
			}

		} catch (ParseException e) {
			e.printStackTrace();
		}
		return BmsProjectList;
	}

	/**
	 *  项目地区转换
	 * @param area
	 * @return
	 */
	private String areaTransform(String area) {
		String areas = "";
		if(StringUtils.isNotBlank(area)){
			String[] areaStr = area.split(",");
			for (String item : areaStr) {
				List<BmsMdArea> bmsMdAreas = bmsMdAreaMapper.selectBmsMdAreaListByName(item);
				if(!CollectionUtils.isEmpty(bmsMdAreas)){
					areas += bmsMdAreas.get(0).getGuid()+";";
				}
			}
		}
		log.info("区域信息原"+area+"，区域信息现："+areas);
		return areas;
	}

	/**
	 * 调用BPM接口，取消未完成流程
	 * @param bmsWorkflow
	 */
	@Override
	public void cancelInstance(BmsWorkflow bmsWorkflow){
		//当前项目或业务下所有未完成流程
		List<String> list = bmsWorkflowMapper.selectBmsWorkflowListAndStatusUnfinished(bmsWorkflow);
		if(CollectionUtils.isEmpty(list)){
			return;
		}
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("systemCode",systemCode);
		paramMap.put("secret",secret);
		String instanceIds = "";
		for (String instanceId : list) {
			if(StringUtils.isNotBlank(instanceId)){
				instanceIds += instanceId+";";
			}
		}
		paramMap.put("instanceId",instanceIds);
		Map<String, Object> stringObjectMap = ThreadPost.doPost2Request(baseUrl+cancelInstanceUrl, JSONUtils.toJson(paramMap), null);
		if(null!=stringObjectMap&&(Integer)stringObjectMap.get("code")==200){
			//修改未完成流程状态为2取消状态
			bmsWorkflowMapper.updateBmsWorkflowStatus(list);
		}
	}

	@Override
	public boolean checkProjectStatus(String projectId) {
		String status = bmsProjectMapper.checkProjectStatus(projectId);
		if(StringUtils.isNotBlank(status)) {
			if("已结项".equals(status) || "结项流转中".equals(status) || "项目作废".equals(status)) {
				return false;
			}else {
				return true;
			}
		}else {
			return true;
		}

	}

	@Override
	public int checkUserIsMember(String projectId, String userId,String jobNo) {
		int res = bmsProjectMapper.checkUserIsMember(projectId, userId, jobNo);
		return res;
	}

	@Override
	public int checkUserIsMemberList(String userId,String jobNo) {
		int res = bmsProjectMapper.checkUserIsMemberList(userId, jobNo);
		return res;
	}



}
